using GameLogic.Localization;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace GameLogic
{
    public class OpeningDialog : MonoBehaviour
    {
        int m_Cursor = 0;
        string m_Speak;
        float m_TimeCount = 0;
        [SerializeField]
        float m_TimeCountMax = 0.1f;
        bool m_IsContinueMode = false;

        [SerializeField]
        bool m_CloseDialogWhenCompleted = true;

        TextMeshProUGUI m_SpeakT;
        [SerializeField]
        UnityEvent m_OnFinished = new UnityEvent();

        Button m_Btn;
        Image m_Mask;
        bool m_IsCompleted = false;
        [SerializeField]
        bool m_NeverStopPlay = true;
        void Awake()
        {
            m_Mask = GetComponent<Image>();
            var m_Btn = GetComponent<Button>();
            if (m_Btn)
                m_Btn.onClick.AddListener(OnClicked);
            m_SpeakT = GetComponentInChildren<TextMeshProUGUI>();

            GetComponent<TextMeshProUGUI>();
        }

        // Update is called once per frame
        void Update()
        {
            if (m_IsCompleted)
                return;
            m_TimeCount += Time.deltaTime;
            if (m_TimeCount > m_TimeCountMax && 
                m_Cursor <= m_Speak.Length)
            {
                m_TimeCount = 0;
                m_SpeakT.text = m_Speak.Substring(0, m_Cursor);
                m_Cursor++;
            }
            if (m_IsContinueMode)
                m_Mask.raycastTarget = m_Cursor < m_Speak.Length;
            else
                m_Mask.raycastTarget = true;

        }

        public void Play(string speak)
        {
           m_Speak = speak;
            gameObject.SetActive(true);
            m_SpeakT.text = "";
            m_Cursor = 0;
            m_IsCompleted = false;
        }
        public void SetContinueMode(bool isContinueMode)
        {
            m_IsContinueMode = isContinueMode;
        }

        public void OnClicked()
        {
            if (m_IsCompleted)
                return;
            if (m_Cursor < m_Speak.Length)
            {
                m_Cursor = m_Speak.Length;
                m_TimeCount = 1000;
            }
            else if(m_OnFinished != null)
            {
                if(m_CloseDialogWhenCompleted)
                    gameObject.SetActive(false);
                m_OnFinished.Invoke();
                m_Cursor = 0;
                if(!m_NeverStopPlay)
                    m_IsCompleted = true;
            }
        }
    }
}
